/*
 * assignment01.asm
 *
 *  Created: 2/7/2015 12:21:23 AM
 *   Author: Jeevake Attapattu
 */ 

.INCLUDE "M328PDEF.INC"

;a) Store 25 numbers starting from the RAMEND location. Capture the lower 8bits of the RAM MIDDLE = (RAMBEGIN + RAMEND)/2 address and use them as your values. You can increment or decrement from RAM MIDDLE location to get the subsequent 24 numbers. Make sure the sum is not greater than 16-bits. Use the X/Y/Z registers to fill up the stack of 25 numbers.
	
	;initialize stack
	LDI R16, HIGH(RAMEND)
	OUT SPH, R16
	LDI R16, LOW(RAMEND)
	OUT SPL, R16
	
	;LOAD RAM BEGIN TO X
	LDI R27, HIGH(0x0100)
	LDI R26, LOW(0x0100)
	;RAMEND TO Y
	LDI R29, HIGH(RAMEND)
	LDI R28, LOW(RAMEND)
	ADD R27, R29    ;ADD RAM END AND RAM BEGIN
	ADC R26, R28
	ROR R27        ;DEVIDE R27 BY TWO
	ROR R26
	;X HOLDS RAM MIDDLE Y HOLDS RAMEND
	
	LDI R16, 25 ;LOAD COUNTER
	LDI R31, HIGH(0x0100)	;USE Z FOR RAMBEGIN POINTER
	LDI R30, LOW(0x0100)
KPSTR:
	ST Z, R26     ;STORE X TO LOCATION Z
	ADIW Z, 1	;INCREMENT STORAGE LOCATION
	SBIW X, 1   ;DECREMENT RAM MIDDLE
	DEC R16     ;DECREMENT COUNTER
	BRNE KPSTR


	LDI R19, 25 ;LOAD COUNTER
	LDI R17, 0 ;CLEAR R17
	;Y HOLDS LOCATION
	LDI R29, HIGH(0X0100)
	LDI R28, LOW(0X0100)
KEEPADDIN:
;b) Parse through the 25 numbers and add all numbers divisible by 7 and place the result in R20:21.
	;R16 HOLDS VALUE
	LD R16, Y
	ADIW Y, 1
	;MOV COPY OF VALUE TO R17:R18
	MOV R18, R16
	
CHECKDIV7:
	SUBI R16, 7		;SUBSTRACT 7
	BREQ DIV7		;IF REMAINDER IS ZERO BRANCH TO SUM
	BRCS NOTDIV7	;IF REMAINDER IS NEGATIVE BYPASS SUM
	JMP CHECKDIV7	;KEEP CHECKING DIVISION
DIV7:
	ADD R21, R18	;ADD DIVIBLE NUMBERS TO RUNNING SUM    
	ADC R20, R17
NOTDIV7:

;c) Parse through the 25 numbers and add all numbers divisible by 3 and place the result in R23:24. Parsing of the numbers for task b and c has to be done simultaneously.

	;MOV COPY OF VALUE TO R16
	MOV R16, R18
CHECKDIV3:
	SUBI R16, 3		;SUBSTRACT 3
	BREQ DIV3	    ;CHECK IF REMAINDER IS ZERO
	BRCS NOTDIV3	;IF NEGATIVE BRANCH TO BYPASS SUM
	JMP CHECKDIV3	;KEEP CHECKING FOR DEVISION
DIV3:
	ADD R24, R18    	;ADD DIVIBLE NUMBERS TO RUNNING SUM 
	ADC R23, R17

NOTDIV3:
	DEC R19     ;DECREMENT COUNTER
	BRNE KEEPADDIN

END:
	JMP END
;d) Determine the execution time @ 16MHz /#cycles of your algorithm using the simulation. 